// vars/sshDeploy.groovy

def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config

    body()

    properties([parameters([choice(choices: ['dev', 'pro'], description: '构建环境', name: 'PROFILE')])])

    assert(config.APP_NAME)
    assert(config.HOSTS)
    assert(config.REMOTE_PATH)

    /* 构建环境 */
    def PFILE = params.PROFILE
    /* 各环境部署服务器,一个环境部署多个主机使用逗号隔开 */
    def SVRS_ENV = config.HOSTS
    def SVRS = SVRS_ENV["${PFILE}"]   
    def SERVERS = SVRS.split(',')   
    def APP_NAME = config.APP_NAME
    def REMOTE_APP_PATH = config.REMOTE_PATH  + "/" + APP_NAME
    def MVN_NAME = config.MVN
    def MVN_SETTINGS = config.MVN_SETTINGS
    def MVN_ARGS = config.MVN_ARGS

    def MVN_DEPLOY = true
    def MICRO_SERVICE = false
    def TARGET_DIR = "./target"

    if(config.MICRO_SERVICE){
        MICRO_SERVICE = true
        TARGET_DIR = "./"+ APP_NAME +"/target"
    }else{
        MICRO_SERVICE = false
        TARGET_DIR = "./target"
    }

    def JAR_FILE = TARGET_DIR + '/' + APP_NAME + '.jar'
    def SHELL_FILE = TARGET_DIR + '/run.sh'
            
    if(MVN_SETTINGS == null){
        MVN_SETTINGS = 'settings.xml'
    }
 
    if(MVN_NAME == null){
        MVN_NAME = 'maven3'
    }

    if(MVN_ARGS==null){
      MVN_ARGS=''
    }

    stage('Checkout') {
      checkout scm    
    }

    def mvnHome
    stage('Build') {
      sh "mvn -U -Dmaven.test.skip=true -P${PFILE} -Dmaven.test.failure.ignore clean package install deploy ${MVN_ARGS}"
    }

    if(MVN_DEPLOY){
        stage('Deploy') {
            for(int i=0;i<SERVERS.length;i++){
                def svr = SERVERS[i];
                println svr
                def item = svr.split('@')
                def user = item[0]
                def host = item[1]

                println REMOTE_APP_PATH
                /* 确认远程主机目录已创建 */
                sh """ssh -Tq ${svr} <<EOF
                      echo ${REMOTE_APP_PATH} 
                      mkdir -p ${REMOTE_APP_PATH}
EOF"""
                
                /* 将应用部署到远程主机 */                        
                def targetDir = svr + ":" + REMOTE_APP_PATH
                sh """scp ${JAR_FILE} ${targetDir}     
                      scp ${SHELL_FILE} ${targetDir}
                      ssh -Tq ${svr} <<EOF
                      cd ${REMOTE_APP_PATH}/
                      chmod +x *.sh
                      ${REMOTE_APP_PATH}/run.sh restart ${PFILE}
EOF"""
            }                 
        }
    }


}